package cloudContact.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.mybeans.factory.RollbackException;

import cloudContact.Common;
import cloudContact.GoogleConstant;
import cloudContact.MyDAOException;
import cloudContact.SecurityManager;
import cloudContact.DAO.GoogleContact;
import cloudContact.DAO.GoogleContactDAO;
import cloudContact.DAO.User;
import cloudContact.DAO.UserDAO;

import com.google.gdata.client.authn.oauth.GoogleOAuthParameters;
import com.google.gdata.client.authn.oauth.OAuthException;
import com.google.gdata.util.ServiceException;

/**
 * Servlet implementation class UpdateContact
 */
@WebServlet("/UpdateContact")
public class UpdateContact extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UpdateContact() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println("Start UpdateContact...");

		response.setContentType("text/plain");
		PrintWriter out = response.getWriter();

		try {
			if (!SecurityManager.CheckAuthorization(request)) {
				out.println("Error: User is not authorized.");
				return;
			}

			HttpSession session = request.getSession();
			User user = null;
			try {
				user = UserDAO.getInstance().lookup(
						session.getAttribute("userId").toString());
			} catch (RollbackException e) {
				e.printStackTrace();
			} catch (MyDAOException e) {
				e.printStackTrace();
			}

			if (user == null) {
				out.println("Error: User not found.");
				return;
			}

			GoogleOAuthParameters oauthParameters = GoogleConstant
					.getGoogleOAuthParameters(user.getGMailAccessToken(),
							user.getGMailAuthSecrete(), user.getUserId());

			String contactId = request.getParameter("id").replace("\\/", "/")
					.replace("@", "%40");
			System.out.println("contact ID = " + contactId);

			GoogleContactDAO gContactDAO = GoogleContactDAO
					.getInstanceForSession(session.getId(), oauthParameters);

			GoogleContact contact = gContactDAO.lookup(contactId);
			
			String address = request.getParameter("address");
			if (address != null && !address.equals(""))
				contact.setAddress(address);
			
			//contact.setBirthday(request.getParameter("birthday"));
			String email = request.getParameter("email");
			if (email != null && !email.equals(""))
				contact.setEmail(email);
			
			String mobile = request.getParameter("mobile");
			if (mobile != null && !mobile.equals(""))
				contact.setMobilePhone(mobile);
			
			String name = request.getParameter("name");
			if (name != null && !name.equals(""))
				contact.setFullName(name);
			
			String facebook = request.getParameter("facebook");
			if (facebook != null && !facebook.equals(""))
				contact.setFacebookURL(facebook);
			
			String notes = request.getParameter("notes");
			if (notes != null && !notes.equals(""))
				contact.setNotes(notes);

			gContactDAO.update(contact);
			
			out.print(true);
		} catch (OAuthException e) {
			out.print(Common.CriticalErrorRaised(e));
		} catch (ServiceException e) {
			out.print(Common.CriticalErrorRaised(e));
		} catch (RollbackException e) {
			out.print(Common.CriticalErrorRaised(e));
		} catch (MyDAOException e) {
			out.print(Common.CriticalErrorRaised(e));
		} finally {
			out.flush();
			out.close();
			System.out.println("Finish UpdateContact.");
		}

	}

}
